<template>
  <view class="history-page">


    <!-- 操作栏 -->
    <view class="action-bar">
      <view class="clear-btn" @click="showClearConfirm">
        <u-icon name="trash" size="16" color="#999"></u-icon>
        <text class="clear-text">清空历史</text>
      </view>
    </view>

    <!-- 历史记录列表 -->
    <view class="history-list" v-if="historyList.length > 0">
      <view 
        class="history-item" 
        v-for="item in historyList" 
        :key="item.id"
        @click="goToDetail(item)"
      >
        <view class="product-image">
          <image 
            :src="item.image || '/static/images/default-product.png'" 
            mode="aspectFill"
            class="product-img"
          />
        </view>
        
        <view class="product-info">
          <view class="product-name">{{ item.product_name || item.name }}</view>
          <view class="product-category">{{ item.category || '其他' }}</view>
          <view class="product-price">¥{{ formatPrice(item.product_price || item.price) }}</view>
          <view class="view-time">{{ formatTime(item.view_time || item.create_time) }}</view>
        </view>
        
        <view class="action-buttons">
          <view class="delete-btn" @click.stop="deleteHistory(item)">
            <u-icon name="close" size="14" color="#999"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && historyList.length === 0">
      <u-empty 
        text="暂无浏览历史" 
        icon="clock"
        mode="data"
      >
        <view slot="bottom" class="empty-tip">
          <text>浏览商品后会在这里显示记录</text>
        </view>
      </u-empty>
    </view>

    <!-- 加载更多 -->
    <u-loadmore 
      :status="loadmoreStatus" 
      @loadmore="loadMore"
      v-if="historyList.length > 0"
    />

    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading && historyList.length === 0">
      <u-loading-icon mode="spinner" size="60" color="#007AFF"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 清空确认弹窗 -->
    <u-modal 
      v-model="clearConfirmShow" 
      title="确认清空" 
      content="确定要清空所有浏览历史吗？此操作不可恢复。"
      show-cancel-button
      @confirm="clearAllHistory"
      @cancel="clearConfirmShow = false"
    />
  </view>
</template>

<script>
/**
 * 用户浏览历史页面
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { productApi } from '@/api'
import { showToast, handleApiError, formatPrice, formatTime } from '@/utils/common.js'

export default {
  data() {
    return {
      historyList: [],
      loading: false,
      loadmoreStatus: 'loadmore',
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      clearConfirmShow: false
    }
  },
  
  onLoad() {
    this.loadHistoryList()
  },
  
  onShow() {
    // 从其他页面返回时刷新数据
    this.refreshList()
  },
  
  onPullDownRefresh() {
    this.refreshList()
  },
  
  onReachBottom() {
    this.loadMore()
  },
  
  methods: {

    
    /**
     * 刷新列表
     */
    refreshList() {
      this.currentPage = 1
      this.hasMore = true
      this.historyList = []
      this.loadHistoryList()
    },
    
    /**
     * 加载浏览历史列表
     */
    async loadHistoryList() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      this.loadmoreStatus = 'loading'
      
      try {
        // 检查登录状态
        const userToken = uni.getStorageSync('user_token')
        if (!userToken) {
          this.loading = false
          this.loadmoreStatus = 'loadmore'
          showToast('请先登录查看浏览历史')
          return
        }
        
        const params = {
          user_token: userToken,
          page: this.currentPage,
          limit: this.pageSize
        }
        
        const response = await productApi.getUserViewHistory(params)
        
        if (response.code === 0 && response.data) {
          let newList = []
          
          // 处理不同的数据格式
          if (Array.isArray(response.data)) {
            newList = response.data
          } else if (response.data.list && Array.isArray(response.data.list)) {
            newList = response.data.list
          } else if (response.data.data && Array.isArray(response.data.data)) {
            newList = response.data.data
          }
          
          // 数据格式化
          const formattedList = newList.map(item => ({
            id: item.id || item.product_id,
            product_id: item.product_id || item.id,
            product_name: item.product_name || item.name,
            name: item.product_name || item.name,
            category: item.category || '其他',
            product_price: parseFloat(item.product_price || item.price || 0),
            price: parseFloat(item.product_price || item.price || 0),
            image: item.image || item.product_image,
            view_time: item.view_time || item.create_time,
            create_time: item.view_time || item.create_time
          }))
          
          if (this.currentPage === 1) {
            this.historyList = formattedList
          } else {
            this.historyList.push(...formattedList)
          }
          
          this.hasMore = formattedList.length >= this.pageSize
          if (this.hasMore) {
            this.currentPage++
          }
          
          this.loadmoreStatus = this.hasMore ? 'loadmore' : 'nomore'
        } else {
          handleApiError(response)
          this.loadmoreStatus = 'loadmore'
        }
      } catch (error) {
        console.error('加载浏览历史失败:', error)
        showToast('加载失败，请重试')
        this.loadmoreStatus = 'loadmore'
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    /**
     * 加载更多
     */
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadHistoryList()
      }
    },
    
    /**
     * 跳转到商品详情
     */
    async goToDetail(item) {
      try {
        if (!item.product_id && !item.id) {
          showToast('商品信息不完整')
          return
        }
        
        const productId = item.product_id || item.id
        const productName = item.product_name || item.name || ''
        const category = item.category || ''
        
        // 跳转到商品详情页
        uni.navigateTo({
          url: `/pages/product/detail?id=${productId}&name=${encodeURIComponent(productName)}&category=${encodeURIComponent(category)}`
        })
      } catch (error) {
        console.error('跳转详情页失败:', error)
        showToast('跳转失败')
      }
    },
    
    /**
     * 删除单条历史记录
     */
    async deleteHistory(item) {
      try {
        uni.showModal({
          title: '确认删除',
          content: '确定要删除这条浏览记录吗？',
          success: async (res) => {
            if (res.confirm) {
              // 这里可以调用删除API，目前先从本地列表移除
              const index = this.historyList.findIndex(h => h.id === item.id)
              if (index > -1) {
                this.historyList.splice(index, 1)
                showToast('删除成功')
              }
            }
          }
        })
      } catch (error) {
        console.error('删除历史记录失败:', error)
        showToast('删除失败')
      }
    },
    
    /**
     * 显示清空确认弹窗
     */
    showClearConfirm() {
      if (this.historyList.length === 0) {
        showToast('暂无历史记录')
        return
      }
      this.clearConfirmShow = true
    },
    
    /**
     * 清空所有历史记录
     */
    async clearAllHistory() {
      try {
        this.clearConfirmShow = false
        
        // 这里可以调用清空API，目前先清空本地列表
        this.historyList = []
        this.currentPage = 1
        this.hasMore = true
        
        showToast('清空成功')
      } catch (error) {
        console.error('清空历史记录失败:', error)
        showToast('清空失败')
      }
    },
    
    /**
     * 格式化价格
     */
    formatPrice(price) {
      return formatPrice(price)
    },
    
    /**
     * 格式化时间
     */
    formatTime(time) {
      return formatTime(time)
    }
  }
}
</script>

<style lang="scss" scoped>
.history-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.clear-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  background-color: #f8f9fa;
}

.clear-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #999;
}

.history-list {
  padding: 0 30rpx;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  margin-right: 30rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #f8f9fa;
}

.product-img {
  width: 100%;
  height: 100%;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-category {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.product-price {
  font-size: 30rpx;
  font-weight: 600;
  color: #ff6b35;
  margin-bottom: 10rpx;
}

.view-time {
  font-size: 24rpx;
  color: #ccc;
}

.action-buttons {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #f8f9fa;
}

.empty-state {
  padding: 200rpx 60rpx;
  text-align: center;
}

.empty-tip {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 999;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}
</style>